package com.wingsoft.generator.service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.*;
import java.util.*;
import java.util.Date;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import cn.hutool.db.DbUtil;
import com.wingsoft.common.utils.IdGenerator.IdGeneratorFactory;
import com.wingsoft.generator.domain.OptionTable;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wingsoft.common.constant.Constants;
import com.wingsoft.common.constant.GenConstants;
import com.wingsoft.common.core.text.CharsetKit;
import com.wingsoft.common.exception.ServiceException;
import com.wingsoft.common.utils.SecurityUtils;
import com.wingsoft.common.utils.StringUtils;
import com.wingsoft.generator.domain.GenTable;
import com.wingsoft.generator.domain.GenTableColumn;
import com.wingsoft.generator.mapper.GenTableColumnMapper;
import com.wingsoft.generator.mapper.GenTableMapper;
import com.wingsoft.generator.util.GenUtils;
import com.wingsoft.generator.util.VelocityInitializer;
import com.wingsoft.generator.util.VelocityUtils;

/**
 * 业务 服务层实现
 * 
 * @author fyadmin
 */
@Service
public class GenTableServiceImpl implements IGenTableService
{
    private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);

    @Autowired
    private GenTableMapper genTableMapper;

    @Autowired
    private GenTableColumnMapper genTableColumnMapper;

    @Autowired(required = false)
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private IdGeneratorFactory idGeneratorFactory;
    @Autowired
    private IGenTableColumnService genTableColumnService;

    /**
     * 查询业务信息
     * 
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTable selectGenTableById(Long id)
    {
        GenTable genTable = genTableMapper.selectGenTableById(id);
        setTableFromOptions(genTable);
        return genTable;
    }

    /**
     * 查询业务列表
     * 
     * @param genTable 业务信息
     * @return 业务集合
     */
    @Override
    public List<GenTable> selectGenTableList(GenTable genTable)
    {
        return genTableMapper.selectGenTableList(genTable);
    }

    /**
     * 查询据库列表
     * 
     * @param genTable 业务信息
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableList(GenTable genTable) {
//        return genTableMapper.selectDbTableList(genTable);

        List<GenTable> genTableList = new ArrayList<>();
        Connection connection = null;
        DatabaseMetaData metaData = null;
        ResultSet tableResultSet = null;
        try {
            connection = jdbcTemplate.getDataSource().getConnection();
            metaData = connection.getMetaData();

            // 获取所有表
            tableResultSet = metaData.getTables(connection.getCatalog(), connection.getSchema(), "%", new String[]{"TABLE"});
//            ResultSetMetaData resultSetMetaData = tableResultSet.getMetaData();
//            int columnCount = resultSetMetaData.getColumnCount();
//            System.out.println("结果集包含 " + columnCount + " 列:");
//            for (int i = 1; i <= columnCount; i++) {
//                String columnLabel = resultSetMetaData.getColumnLabel(i);
//                String columnType = resultSetMetaData.getColumnTypeName(i);
//                System.out.printf("列 %d: 名称=%s, 类型=%s \n", i, columnLabel, columnType);
//            }
            while (tableResultSet.next()) {
                String tableName = tableResultSet.getString("TABLE_NAME");
                String remarks = tableResultSet.getString("REMARKS");
//                System.out.println("Table: " + tableName);
                GenTable tGenTable = new GenTable();
                tGenTable.setTableName(tableName);
                tGenTable.setTableComment(remarks);
                genTableList.add(tGenTable);

                // 获取表字段结构
//                ResultSet columnResultSet = metaData.getColumns(connection.getCatalog(), connection.getSchema(), genTable.getTableName().toUpperCase(), "%");
//                while (columnResultSet.next()) {
//                    String columnName = columnResultSet.getString("COLUMN_NAME");
//                    String columnType = columnResultSet.getString("TYPE_NAME");
//                    int columnSize = columnResultSet.getInt("COLUMN_SIZE");
//                    int decimalDigits = columnResultSet.getInt("DECIMAL_DIGITS");
//                    int nullable = columnResultSet.getInt("NULLABLE");
//                    String remarks = columnResultSet.getString("REMARKS");
//                    System.out.println(columnName + " " + columnType + " " + columnSize + " " + decimalDigits + " " + nullable + " " + remarks);
//                }
//                System.out.println("=================================");
            }
        } catch (SQLException e) {
            log.error("查询据库列表失败", e);
            throw new ServiceException(e.getMessage());
        } finally {
            DbUtil.close(tableResultSet, metaData, connection);
        }
        genTableList = genTableList.stream().filter(o ->
                        !o.getTableName().toLowerCase().startsWith("qrtz_")
                                && !o.getTableName().toLowerCase().startsWith("gen_"))
                .filter(o -> {
                    if (StringUtils.isBlank(genTable.getTableName())) {
                        return true;
                    } else if (StringUtils.isNotBlank(o.getTableName())) {
                        return o.getTableName().toLowerCase().contains(genTable.getTableName().toLowerCase().trim());
                    } else {
                        return false;
                    }
                }).filter(o -> {
                    if (StringUtils.isBlank(genTable.getTableComment())) {
                        return true;
                    } else if (StringUtils.isNotBlank(o.getTableComment())) {
                        return o.getTableComment().toLowerCase().contains(genTable.getTableComment().toLowerCase().trim());
                    } else {
                        return false;
                    }
                })
                .collect(Collectors.toList());

        return genTableList;
    }

    /**
     * 查询据库列表
     * 
     * @param tableNames 表名称组
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames)
    {
//        return genTableMapper.selectDbTableListByNames(tableNames);

        List<GenTable> genTableList = new ArrayList<>();
        for (String tableName : tableNames) {
            GenTable genTable = new GenTable();
            genTable.setTableName(tableName);
            List<GenTable> list = this.selectDbTableList(genTable);
            if(CollectionUtils.isNotEmpty(list)){
                genTableList.addAll(list);
            }
        }
        return genTableList;
    }

    /**
     * 查询所有表信息
     * 
     * @return 表信息集合
     */
    @Override
    public List<GenTable> selectGenTableAll()
    {
        return genTableMapper.selectGenTableAll();
    }

    /**
     * 修改业务
     * 
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateGenTable(GenTable genTable)
    {
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        int row = genTableMapper.updateGenTable(genTable);
        if (row > 0)
        {
            for (GenTableColumn cenTableColumn : genTable.getColumns())
            {
                genTableColumnMapper.updateGenTableColumn(cenTableColumn);
            }
        }
    }

    /**
     * 删除业务对象
     * 
     * @param tableIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteGenTableByIds(Long[] tableIds)
    {
        genTableMapper.deleteGenTableByIds(tableIds);
        genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
    }

    /**
     * 导入表结构
     * 
     * @param tableList 导入表列表
     */
    @Override
    @Transactional
    public void importGenTable(List<GenTable> tableList)
    {
        String operName = SecurityUtils.getUsername();
        try
        {
            for (GenTable table : tableList)
            {
                String tableName = table.getTableName();
                GenUtils.initTable(table, operName);
                table.setCreateTime(new Date());
                table.setTableId(idGeneratorFactory.getId(GenTable.class));
                int row = genTableMapper.insertGenTable(table);
                if (row > 0)
                {
                    // 保存列信息
//                    List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                    List<GenTableColumn> genTableColumns = this.getGenTableColumnList(tableName);
                    for (GenTableColumn column : genTableColumns)
                    {
                        GenUtils.initColumnField(column, table);
                        genTableColumnService.insertGenTableColumn(column);
                    }
                }
            }
        }
        catch (Exception e)
        {
            log.error("导入失败：{}", e.getMessage(), e);
            throw new ServiceException("导入失败：" + e.getMessage());
        }
    }

    /**
     * 预览时组织vm模板的内容
     * @param dataMap
     * @param template
     * @param context
     */
    private void previewMap(Map<String, String> dataMap,String template,VelocityContext context,String subName){
        // 渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, Constants.UTF8);
        tpl.merge(context, sw);
        String name = template.substring(template.lastIndexOf("/") + 1, template.indexOf(".vm"));
        if (ObjectUtils.isEmpty(subName)){
            dataMap.put(name, sw.toString());
        }else {
            dataMap.put(subName + "/" +name, sw.toString());
        }

    }

    /**
     * 预览代码
     * 
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(Long tableId)
    {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableById(tableId);
        //循环表结构，查询选项字段关联的表
        List<OptionTable> optionTables = this.initOptionTables(table);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table,optionTables);

        // 设置主表模板
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates){
            this.previewMap(dataMap,template,context,null);
        }
        //设置子表vue模板
        if (GenConstants.TPL_SUB.equals(table.getTplCategory())){
            List<GenTable> subGenTables = table.getSubTables();
            for (GenTable subGenTable : subGenTables){
                // 设置主键列信息
                setPkColumn(subGenTable);
                List<OptionTable> optionSubTables = this.initOptionTables(subGenTable);
                VelocityContext subContext = VelocityUtils.prepareContext(subGenTable,optionSubTables);
                // 渲染模板
                this.previewMap(dataMap,"vm/vue/subIndex.vue.vm",subContext,subGenTable.getBusinessName());
                //生成子表其他CRUD模板
                List<String> templateSubs = VelocityUtils.getTemplateList(subGenTable.getTplCategory());
                for (String template : templateSubs){
                    this.previewMap(dataMap,template,subContext,subGenTable.getBusinessName());
                }
            }
        }
        return dataMap;
    }


    public void generatorFile(VelocityContext context,String template,GenTable table,ZipOutputStream zip){
        // 渲染模板
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate(template, Constants.UTF8);
        tpl.merge(context, sw);
        try
        {
            // 添加到zip
            zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
            IOUtils.write(sw.toString(), zip, Constants.UTF8);
            IOUtils.closeQuietly(sw);
            zip.flush();
            zip.closeEntry();
        }
        catch (IOException e)
        {
            log.error("渲染模板失败，表名：" + table.getTableName(), e);
        }
    }
    /**
     * 查询表信息并生成代码 下载zip方式
     */
    private void generatorCode(String tableName, ZipOutputStream zip)
    {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        //循环表结构，查询选项字段关联的表
        List<OptionTable> optionTables = this.initOptionTables(table);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table,optionTables);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            this.generatorFile(context,template,table,zip);
        }
        //设置子表模板
        if (GenConstants.TPL_SUB.equals(table.getTplCategory())){
            List<GenTable> subGenTables = table.getSubTables();
            for (GenTable subGenTable : subGenTables){
                // 设置主键列信息
                setPkColumn(subGenTable);
                List<OptionTable> optionSubTables = this.initOptionTables(subGenTable);
                VelocityContext subContext = VelocityUtils.prepareContext(subGenTable,optionSubTables);
                this.generatorFile(subContext,"vm/vue/subIndex.vue.vm",subGenTable,zip);
                //生成子表其他CRUD模板
                List<String> templateSubs = VelocityUtils.getTemplateList(subGenTable.getTplCategory());
                for (String template : templateSubs)
                {
                    this.generatorFile(subContext,template,subGenTable,zip);
                }
            }
        }
    }

    /**
     * 获取表单中的下拉选择
     * @param table
     * @return
     */
    public List<OptionTable> initOptionTables(GenTable table){
        List<GenTableColumn> genTableColumns = table.getColumns();
        Map<String,OptionTable> optionTableMap = new LinkedHashMap<>();
        for (GenTableColumn column : genTableColumns){
            if (!ObjectUtils.isEmpty(column.getOptionType()) && column.getOptionType() == 2 && !ObjectUtils.isEmpty(column.getOptionTable())){
                GenTable genTable = genTableMapper.selectGenTableByName(column.getOptionTable());
                OptionTable optionTable = optionTableMap.get(genTable.getBusinessName());
                if (optionTable == null){
                    optionTable = new OptionTable();
                    optionTable.setBusinessName(genTable.getBusinessName());
                    optionTable.setModuleName(genTable.getModuleName());
                    optionTable.setBusinessNameUpper(StringUtils.capitalize(genTable.getBusinessName()));
                }
                List<String> columnJavaField = optionTable.getColumnJavaField();
                columnJavaField.add(column.getJavaField());
                optionTable.setColumnJavaField(columnJavaField);
                optionTableMap.put(genTable.getBusinessName(), optionTable);
            }
        }
        List<OptionTable> optionTables = new ArrayList<>(optionTableMap.values());
        return optionTables;
    }

    /**
     * 生成代码（下载方式）
     * 
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String tableName)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 生成代码（自定义路径）
     * 
     * @param tableName 表名称
     */
    @Override
    public void generatorCode(String tableName)
    {
        // 查询表信息
        GenTable table = genTableMapper.selectGenTableByName(tableName);

        //循环表结构，查询选项字段关联的表
        List<OptionTable> optionTables = this.initOptionTables(table);
        // 设置主子表信息
        setSubTable(table);
        // 设置主键列信息
        setPkColumn(table);

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table,optionTables);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
        for (String template : templates)
        {
            if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm"))
            {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, Constants.UTF8);
                tpl.merge(context, sw);
                try
                {
                    String path = getGenPath(table, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                }
                catch (IOException e)
                {
                    throw new ServiceException("渲染模板失败，表名：" + table.getTableName());
                }
            }
        }
    }

    /**
     * 同步数据库
     * 
     * @param tableName 表名称
     */
    @Override
    @Transactional
    public void synchDb(String tableName)
    {
        GenTable table = genTableMapper.selectGenTableByName(tableName);
        List<GenTableColumn> tableColumns = table.getColumns();
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));

//        List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
        List<GenTableColumn> dbTableColumns = this.getGenTableColumnList(tableName);
        if (StringUtils.isEmpty(dbTableColumns))
        {
            throw new ServiceException("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        dbTableColumns.forEach(column -> {
            GenUtils.initColumnField(column, table);
            if (tableColumnMap.containsKey(column.getColumnName()))
            {
                GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
                column.setColumnId(prevColumn.getColumnId());
                if (column.isList())
                {
                    // 如果是列表，继续保留查询方式/字典类型选项
                    column.setDictType(prevColumn.getDictType());
                    column.setQueryType(prevColumn.getQueryType());
                }
                if (StringUtils.isNotEmpty(prevColumn.getIsRequired()) && !column.isPk()
                        && (column.isInsert() || column.isEdit())
                        && ((column.isUsableColumn()) || (!column.isSuperColumn())))
                {
                    // 如果是(新增/修改&非主键/非忽略及父属性)，继续保留必填/显示类型选项
                    column.setIsRequired(prevColumn.getIsRequired());
                    column.setHtmlType(prevColumn.getHtmlType());
                }
                genTableColumnMapper.updateGenTableColumn(column);
            }
            else
            {
                genTableColumnService.insertGenTableColumn(column);
            }
        });

        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(delColumns))
        {
            genTableColumnMapper.deleteGenTableColumns(delColumns);
        }
    }

    /**
     * 批量生成代码（下载方式）
     * 
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String[] tableNames)
    {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames)
        {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }



    /**
     * 修改保存参数校验
     * 
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(GenTable genTable)
    {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
        {
            String options = JSON.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSON.parseObject(options);
            if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE)))
            {
                throw new ServiceException("树编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE)))
            {
                throw new ServiceException("树父编码字段不能为空");
            }
            else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME)))
            {
                throw new ServiceException("树名称字段不能为空");
            }
            else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory()))
            {
                if (StringUtils.isEmpty(genTable.getSubTableName()))
                {
                    throw new ServiceException("关联子表的表名不能为空");
                }
                else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
                {
                    throw new ServiceException("子表关联的外键名不能为空");
                }
            }
        }
    }

    /**
     * 执行创建或变更表的DDL语句
     * 仅允许以 CREATE 或 ALTER 开头的语句；按分号分割依次执行
     */
    @Override
    @Transactional
    public void createTable(String sql)
    {
        if (StringUtils.isBlank(sql))
        {
            throw new ServiceException("SQL不能为空");
        }
        if (jdbcTemplate == null)
        {
            throw new ServiceException("JdbcTemplate未配置");
        }
        // 兼容URL传递的换行与+号
        String normalized = sql.replaceAll("\\r", "\n");
        // 按分号切分，但保留可能的最后一条无分号结尾
        String[] statements = normalized.split(";\\s*\n?|;\\s*$");
        for (String stmt : statements)
        {
            String trimmed = stmt.trim();
            if (trimmed.isEmpty())
            {
                continue;
            }
            String upper = trimmed.toUpperCase();
            if (!(upper.startsWith("CREATE") || upper.startsWith("ALTER")))
            {
//                throw new ServiceException("仅支持执行CREATE/ALTER语句");
            }
            try
            {
                jdbcTemplate.execute(trimmed);
            }
            catch (Exception e)
            {
                throw new ServiceException("执行DDL失败: " + e.getMessage());
            }
        }
    }

    /**
     * 设置主键列信息
     * 
     * @param table 业务表信息
     */
    public void setPkColumn(GenTable table)
    {
        for (GenTableColumn column : table.getColumns())
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(table.getColumns().get(0));
        }
/*        if (GenConstants.TPL_SUB.equals(table.getTplCategory()))
        {
            for (GenTableColumn column : table.getSubTable().getColumns())
            {
                if (column.isPk())
                {
                    table.getSubTable().setPkColumn(column);
                    break;
                }
            }
            if (StringUtils.isNull(table.getSubTable().getPkColumn()))
            {
                table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
            }
        }*/
    }

    /**
     * 设置主子表信息
     * 
     * @param table 业务表信息
     */
    public void setSubTable(GenTable table)
    {
        String subTableName = table.getSubTableName();
        String subTableFkName = table.getSubTableFkName();
        if (StringUtils.isNotEmpty(subTableName))
        {
            String[] subTableNames = subTableName.split(",");
            String[] subTableFkNames = subTableFkName.split(",");
            List<GenTable> genTables = new ArrayList<>();
            for (int i = 0; i < subTableNames.length; i++){
                GenTable genTable = genTableMapper.selectGenTableByName(subTableNames[i]);
                GenTableColumn fkColumn = genTableColumnMapper.getGenTableColumnByColumnName(genTable.getTableId(), subTableFkNames[i]);
                genTable.setFkColumn(fkColumn);
                genTable.setBusinessNameUpper(StringUtils.capitalize(genTable.getBusinessName()));

                //设定外键字段
                List<GenTableColumn> genTableColumns = genTable.getColumns();
                for (GenTableColumn genTableColumn:genTableColumns){
                    if (genTableColumn.getJavaField().equals(fkColumn.getJavaField())){
                        genTableColumn.setIsFk("1");
                    }
                }
                genTables.add(genTable);
            }
            table.setSubTables(genTables);
        }
    }

    /**
     * 设置代码生成其他选项值
     * 
     * @param genTable 设置后的生成对象
     */
    public void setTableFromOptions(GenTable genTable)
    {
        JSONObject paramsObj = JSON.parseObject(genTable.getOptions());
        if (StringUtils.isNotNull(paramsObj))
        {
            String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(GenConstants.TREE_NAME);
            String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);

            genTable.setTreeCode(treeCode);
            genTable.setTreeParentCode(treeParentCode);
            genTable.setTreeName(treeName);
            genTable.setParentMenuId(parentMenuId);
            genTable.setParentMenuName(parentMenuName);
        }
    }

    /**
     * 获取代码生成地址
     * 
     * @param table 业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, String template)
    {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/"))
        {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table);
    }

    private List<GenTableColumn> getGenTableColumnList(String tableName) {
        Connection connection = null;
        DatabaseMetaData metaData = null;
        ResultSet tableResultSet = null;
        ResultSetMetaData resultSetMetaData = null;
        List<GenTableColumn> genTableColumnList = new ArrayList<>();
        try {
            connection = jdbcTemplate.getDataSource().getConnection();
            metaData = connection.getMetaData();
            ResultSet primaryKeysResultSet = metaData.getPrimaryKeys(connection.getCatalog(), connection.getSchema(), tableName);
            List<String> pkColumnList = new ArrayList<>();
            while (primaryKeysResultSet.next()) {
                String pkColumnName = primaryKeysResultSet.getString("COLUMN_NAME");
                pkColumnList.add(pkColumnName);
            }

            // 获取表字段结构
            ResultSet columnResultSet = metaData.getColumns(connection.getCatalog(), connection.getSchema(), tableName, "%");
//                resultSetMetaData = columnResultSet.getMetaData();
//                int columnCount = resultSetMetaData.getColumnCount();
//                System.out.println("结果集包含 " + columnCount + " 列:");
//                for (int i = 1; i <= columnCount; i++) {
//                    String columnLabel = resultSetMetaData.getColumnLabel(i);
//                    String columnType = resultSetMetaData.getColumnTypeName(i);
//                    System.out.printf("列 %d: 名称=%s, 类型=%s \n", i, columnLabel, columnType);
//                }
            while (columnResultSet.next()) {
                // 结果集包含 24 列:
                //列 1: 名称=TABLE_CAT, 类型=VARCHAR2
                //列 2: 名称=TABLE_SCHEM, 类型=VARCHAR2
                //列 3: 名称=TABLE_NAME, 类型=VARCHAR2
                //列 4: 名称=COLUMN_NAME, 类型=VARCHAR2
                //列 5: 名称=DATA_TYPE, 类型=NUMBER
                //列 6: 名称=TYPE_NAME, 类型=VARCHAR2
                //列 7: 名称=COLUMN_SIZE, 类型=NUMBER
                //列 8: 名称=BUFFER_LENGTH, 类型=NUMBER
                //列 9: 名称=DECIMAL_DIGITS, 类型=NUMBER
                //列 10: 名称=NUM_PREC_RADIX, 类型=NUMBER
                //列 11: 名称=NULLABLE, 类型=NUMBER
                //列 12: 名称=REMARKS, 类型=VARCHAR2
                //列 13: 名称=COLUMN_DEF, 类型=LONG
                //列 14: 名称=SQL_DATA_TYPE, 类型=NUMBER
                //列 15: 名称=SQL_DATETIME_SUB, 类型=NUMBER
                //列 16: 名称=CHAR_OCTET_LENGTH, 类型=NUMBER
                //列 17: 名称=ORDINAL_POSITION, 类型=NUMBER
                //列 18: 名称=IS_NULLABLE, 类型=VARCHAR2
                //列 19: 名称=SCOPE_CATALOG, 类型=VARCHAR2
                //列 20: 名称=SCOPE_SCHEMA, 类型=VARCHAR2
                //列 21: 名称=SCOPE_TABLE, 类型=VARCHAR2
                //列 22: 名称=SOURCE_DATA_TYPE, 类型=VARCHAR2
                //列 23: 名称=IS_AUTOINCREMENT, 类型=CHAR
                //列 24: 名称=IS_GENERATEDCOLUMN, 类型=VARCHAR2
                String columnName = columnResultSet.getString("COLUMN_NAME");
                String isRequired = Objects.equals(columnResultSet.getInt("NULLABLE"), 0) ? "1" : "0";
                String isPk = pkColumnList.contains(columnName) ? "1" : "0";
                int sort = columnResultSet.getInt("ORDINAL_POSITION");
                String columnComment = columnResultSet.getString("REMARKS");
                String isAutoincrement = Objects.equals(columnResultSet.getString("IS_AUTOINCREMENT"), "YES") ? "1" : "0";
                String typeName = columnResultSet.getString("TYPE_NAME");
                int columnSize = columnResultSet.getInt("COLUMN_SIZE");
                int decimalDigits = columnResultSet.getInt("DECIMAL_DIGITS");
                GenTableColumn genTableColumn = new GenTableColumn();
                genTableColumn.setColumnName(columnName);
                genTableColumn.setIsRequired(isRequired);
                genTableColumn.setIsPk(isPk);
                genTableColumn.setSort(sort);
                genTableColumn.setColumnComment(columnComment);
                genTableColumn.setIsIncrement(isAutoincrement);
                if (typeName.contains("(") && typeName.contains(")")) {
                    genTableColumn.setColumnType(typeName);
                } else {
                    if (decimalDigits > 0) {
                        genTableColumn.setColumnType(typeName + "(" + columnSize + "," + decimalDigits + ")");
                    } else {
                        genTableColumn.setColumnType(typeName + "(" + columnSize + ")");
                    }
                }
                genTableColumnList.add(genTableColumn);
            }
        } catch (SQLException e) {
            log.error("查询据库字段列表失败", e);
            throw new ServiceException(e.getMessage());
        } finally {
//            DbUtil.close(connection, metaData, tableResultSet, resultSetMetaData);
        }

        return genTableColumnList;
    }
}